package cool.taomu.toolkit.lmdb

import com.google.inject.Inject
import com.google.inject.Provider
import com.google.inject.name.Named
import java.io.File
import org.apache.commons.lang3.StringUtils
import org.eclipse.xtend.lib.annotations.ToString
import org.lmdbjava.Env
import org.slf4j.LoggerFactory
import java.nio.ByteBuffer
import static org.lmdbjava.ByteBufferProxy.PROXY_OPTIMAL

@ToString
class LmdbProvider implements Provider<Env<ByteBuffer>> {
    val static LOG = LoggerFactory.getLogger(LmdbProvider);

    @Inject(optional=true)
    @Named("taomu.store.lmdb.path")
    String path = "./";

    @Inject(optional=true)
    @Named("taomu.store.lmdb.maxSize")
    Long maxSize = 1_073_741_824L;

    @Inject(optional=true)
    @Named("taomu.store.lmdb.maxDbs")
    Integer maxDbs = 1;

    @Inject(optional=true)
    @Named("taomu.store.lmdb.maxReaders")
    Integer maxReaders;

    override get() {
        LOG.info(LmdbProvider.toString());
        if (StringUtils.isNotBlank(path)) {
            var lmdbPath = new File(path);
            var flag = lmdbPath.exists;
            if (!flag) {
                flag = lmdbPath.mkdirs;
            }
            if (flag) {
                var env = Env.create(PROXY_OPTIMAL).setMapSize(this.maxSize).setMaxDbs(this.maxDbs)
                if (this.maxReaders !== null && this.maxReaders > 0) {
                    env.setMaxReaders(this.maxReaders)
                }
                return env.open(lmdbPath);
            }
        }
        return null;
    }

}
